<template>
  <div>
    <!-- 导航 -->
    <Nav>
      <el-breadcrumb-item
        slot="nav"
        v-for="(item,index) in breadcrumbList"
        :key="index"
        :to="{ path : item.href}"
      >{{item.name}}</el-breadcrumb-item>
    </Nav>
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <!-- 表单内容 -->
      <el-table :data="rolesList" style="width: 100%" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bBottom',i1 === 0 ? 'bTop':'','vecenter']"
            >
              <!-- 第一级 -->
              <el-col :span="5">
                <el-tag class="el-tage" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 第二级和第三级 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '':'bTop','vecenter']"
                >
                  <!-- 第二级 -->
                  <el-col :span="8">
                    <el-tag type="success" closable>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三级 -->
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRolesById(scope.row.id,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{item3.id}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column width="80"></el-table-column>
        <el-table-column width="80" type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="assignPermissions(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="rolesDialogVisible" width="50%" @close="colseRightsList">
      <el-tree
        :data="rightsList"
        :props="defaultProps"
        ref="rightsListRef"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="checkedKey"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Nav from '../nav'
export default {
  data() {
    return {
      breadcrumbList: [
        {
          name: '首页',
          href: '/welcome',
        },
        {
          name: '权限管理',
        },
        {
          name: '角色列表',
        },
      ],
      rolesList: [],
      // 分配权限对话框
      rolesDialogVisible: false,
      // 分配权限列表
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选中的节点
      checkedKey: [],
      // 即将分配的权限id
      rolesId: '',
    }
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 删除角色标签
    async removeRolesById(roleId, rightId) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmRes != 'confirm') return this.$message.info('用户取消了删除')
      const { data: res } = await this.$http.delete(
        'roles/' + roleId + '/rights/' + rightId
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('取消权限失败')
      }
      this.$message.success('删除权限成功')
      this.getRolesList()
    },
    // 分配权限
    async assignPermissions(roles) {
      this.rolesId = roles.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200)
        return this.$message.error('获取分配列表权限失败')
      this.rightsList = res.data
      this.getLefDefKey(roles, this.checkedKey)
      this.rolesDialogVisible = true
    },
    // 通过递归 获取角色下所有三级权限的id,并保存到checkedKey数组中
    getLefDefKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLefDefKey(item, arr)
      })
    },
    // 点击关闭权限列表
    colseRightsList() {
      this.checkedKey = []
    },
    // 点击确定分配权限
    async confirmRights() {
      const keys = [
        ...this.$refs.rightsListRef.getCheckedKeys(),
        ...this.$refs.rightsListRef.getHalfCheckedKeys(),
      ]
      const idStr = keys.join(',')
      const {
        data: res,
      } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idStr })
      if (res.meta.status !== 200)
        return this.$message.error('分配用户权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.rolesDialogVisible = false
    },
  },
  created() {
    this.getRolesList()
  },
  components:{
    Nav
  }
}
</script>

<style>
.el-tag {
  margin: 10px;
}
.bTop {
  border-top: 1px solid #eee;
}
.bBottom {
  border-bottom: 1px solid #eee;
}
.vecenter {
  display: flex;
  align-items: center;
}
</style>